package com.blog.common.interceptors;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.blog.common.constant.ResultCode.USER_NOT_LOGGED_IN;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false); // 获取当前请求的Session，如果Session不存在则返回null
        if (session != null && session.getAttribute("account") != null) {
            return true; // 继续请求处理
        }else{            // 用户未登录，重定向到登录页面
            response.sendRedirect("/login");
            response.setStatus(2000);
            return false; // 中断请求}
    }
}
}